package com.ezjie.ielts.module_read;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.ezjie.ielts.R;
import com.ezjie.ielts.constant.Constants;
import com.ezjie.ielts.db.AudioFileDB;
import com.ezjie.ielts.model.AnswerInfo;
import com.ezjie.ielts.model.AudioFile;
import com.ezjie.ielts.model.FullTextInfo;
import com.ezjie.ielts.model.GroupInfo;
import com.ezjie.ielts.model.QuestionInfo;
import com.ezjie.ielts.model.SubmitGroupInfo;
import com.ezjie.ielts.model.SubmitQuestionInfo;
import com.ezjie.ielts.module_read.ReadAllPracticeActivity.OnSwitchListener;
import com.ezjie.ielts.module_read.ReadAllPracticeActivity.OnTouchEventGestureListener;
import com.ezjie.ielts.task.DownLoadListenTask;
import com.ezjie.ielts.util.AnimUtils;
import com.ezjie.ielts.util.AppUtil;
import com.ezjie.ielts.util.DensityUtil;
import com.ezjie.ielts.util.KeyValuePair;
import com.ezjie.ielts.util.LogUtils;
import com.ezjie.ielts.util.NetworkUtil;
import com.ezjie.ielts.util.SDcardUtil;
import com.ezjie.ielts.util.StringUtil;
import com.ezjie.ielts.view.FlowLayout;
import com.ezjie.ielts.widget.MyScrollView;
import com.ezjie.ielts.widget.MyScrollView.OnScrollListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;

/**
 * 所有的题型练习入口
 * 
 * @author chenyunyun
 *
 */
public class AllExercisesFragment extends Fragment implements OnClickListener, OnScrollListener {

	private static final String TAG = AllExercisesFragment.class.getSimpleName();

	private Context mContext;
	private GestureDetector mGestureDetector;

	@ViewInject(R.id.ll_read_exercises_question)
	private LinearLayout ll_read_exercises_question;
	@ViewInject(R.id.btn_read_previous)
	private Button btn_read_previous;
	@ViewInject(R.id.btn_read_next)
	private Button btn_read_next;
	@ViewInject(R.id.ll_read_click_question_point)
	private LinearLayout ll_read_click_question_point;
	@ViewInject(R.id.tv_fill_smalltitle)
	private TextView tv_fill_smalltitle;
	@ViewInject(R.id.scroll_fill_layout)
	private MyScrollView scroll_fill_layout;
	@ViewInject(R.id.ll_read_top)
	private LinearLayout ll_read_top;
	@ViewInject(R.id.tv_read_exercises_title)
	private TextView tv_read_exercises_title;
	@ViewInject(R.id.tv_read_exercises_title_detail)
	private TextView tv_read_exercises_title_detail;
	@ViewInject(R.id.iv_read_exercises_pictrue)
	private ImageView iv_read_exercises_pictrue;
	@ViewInject(R.id.iv_read_exercises_pictrue2)
	private ImageView iv_read_exercises_pictrue2;
	@ViewInject(R.id.tv_read_exercises_content)
	private TextView tv_read_exercises_content;
	@ViewInject(R.id.ll_read_switch_quesition)
	private LinearLayout ll_read_switch_quesition;
	@ViewInject(R.id.ll_read_exercises_pictrue)
	private RelativeLayout ll_read_exercises_pictrue;
	@ViewInject(R.id.ll_read_exercises_pictrue2)
	private RelativeLayout ll_read_exercises_pictrue2;
	@ViewInject(R.id.btn_read_check)
	private Button btn_read_check;
	@ViewInject(R.id.fl_read_btn)
	private FrameLayout fl_read_btn;
	@ViewInject(R.id.layout_audio_play)
	private LinearLayout layout_audio_play;
	@ViewInject(R.id.iv_listen_download)
	private ImageView iv_listen_download;
	@ViewInject(R.id.iv_listen_play)
	private ImageView iv_listen_play;
	@ViewInject(R.id.seekbar_self)
	private SeekBar seekbar_self;
	@ViewInject(R.id.tv_play_time)
	private TextView tv_play_time;
	@ViewInject(R.id.fl_loading)
	private FrameLayout fl_loading;

	private String type;
	private String fromActivity;
	private int myLayoutTop;
	private ArrayList<GroupInfo> data = new ArrayList<GroupInfo>(); // 当前所有题组信息
	private ArrayList<FullTextInfo> origindata = new ArrayList<FullTextInfo>();// 当前所有题组原文信息
	private int mCurrentGroupId = 0; // 当前题组 ID
	private GroupInfo mCurrentGroupInfo; // 当前题组 信息

	private View mView;

	private List<Integer> mAnswerlist = new ArrayList<Integer>(); // 当前题组已经答题的集合
	private List<ImageView> mPointImageView = new ArrayList<ImageView>(); // 切题时右侧提示浮点
	private int mTotalQuestion = 0; // 当前题组 的总问题数
	private int mCurrentQuestion = 0; // 当前题组所在的问题 ID

	private OnTouchEventGestureListener mOnTouchEventGestureListener;
	private List<RadioButton> rblist = new ArrayList<RadioButton>();
	private List<View> mQuestionView = new LinkedList<View>();
	private List<View> mAnswerView = new LinkedList<View>(); // 当前查看题组的答案解析view集合
	private Integer mAnswerCount = 0; // 当前题组答题数
	private int mTotalAnswer = 0; // 当前问题的答案选项总数
	private boolean mIsLookAnswer = false; // 是否正在查看答案解析
	private List<List<String>> mRightAnswer = new ArrayList<List<String>>(); // 当前题组的正确答案列表
	private Map<Integer, List<String>> mMyAnswer = new HashMap<Integer, List<String>>(); // 当前题组所选答案
	private List<String> mMyCurrentAnswer = new ArrayList<String>(); // 当前题目所选的答案

	private OnSwitchListener listener;
	private static DisplayImageOptions options;
	private String mStartTime = "";

	private boolean isScrollBottom;
	private boolean isScrollTop;

	private MediaPlayer mMediaPlayer;
	private DownLoadListenTask downLoadListenTask;
	private boolean mToPlay;

	private Timer mTimer;
	private TimerTask mTimerTask;

	private boolean mUserDagDBar;

	private boolean isDownLoad;

	private AudioFileDB audioFileDB;

	private AlertDialog alertDialog;

	private ArrayList<SubmitQuestionInfo> submitQuestionInfos;

	private Map<Integer, ArrayList<CheckBox>> checkBoxs = new HashMap<Integer, ArrayList<CheckBox>>();
	private Map<Integer, RadioButton> radioButton = new HashMap<Integer, RadioButton>();
	private ListView listView;
	private ArrayList<KeyValuePair<String, Boolean>> items;

	public AllExercisesFragment() {
		super();
	}

	public AllExercisesFragment(String type, OnSwitchListener listener, int dataPosition) {
		this.type = type;
		this.listener = listener;
		mCurrentGroupId = dataPosition;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mContext = getActivity();
		options = new DisplayImageOptions.Builder().showStubImage(R.drawable.default_img) // 设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.default_img) // 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.default_img) // 设置图片加载/解码过程中错误时候显示的图片
				.cacheInMemory() // 是否緩存都內存中
				.cacheOnDisc() // 是否緩存到sd卡上
				.build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mContext).build();
		ImageLoader.getInstance().init(config);
		init();
	}

	private void init() {

		mOnTouchEventGestureListener = new OnTouchEventGestureListener() {

			@Override
			public boolean onTouchEvent(MotionEvent event) {
				boolean result = mGestureDetector.onTouchEvent(event);
				return result;
			}
		};

		mGestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

				// 手势向下 down
				if (isScrollTop && ((e2.getRawY() - e1.getRawY()) > 200)) {
					if (mCurrentQuestion > 0) {
						AnimUtils.downAnim(mContext, mView);
						scroll_fill_layout.scrollTo(0, 0);
						tv_fill_smalltitle.setVisibility(View.GONE);
						if (mIsLookAnswer) {
							mCurrentQuestion = switchLookAnswer(mCurrentQuestion - 1);
						} else {
							mCurrentQuestion = switchChooiseQuestion(mCurrentQuestion - 1);
						}
					}

					// 在此处控制关闭
					return true;
				}
				// 手势向上 up
				if (isScrollBottom && ((e1.getRawY() - e2.getRawY()) > 200)) {
					if (mTotalQuestion - 1 > mCurrentQuestion) {
						AnimUtils.upAnim(mContext, mView);
						scroll_fill_layout.scrollTo(0, 0);
						tv_fill_smalltitle.setVisibility(View.GONE);
						if (mIsLookAnswer) {
							mCurrentQuestion = switchLookAnswer(mCurrentQuestion + 1);
						} else {
							mCurrentQuestion = switchChooiseQuestion(mCurrentQuestion + 1);
						}
					}
					return true;
				}
				return super.onFling(e1, e2, velocityX, velocityY);
			}
		});

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = LayoutInflater.from(mContext).inflate(R.layout.fragment_all_exercises, container, false);

		ViewUtils.inject(this, mView);
		scroll_fill_layout.setOnScrollListener(this);
		btn_read_next.setOnClickListener(this);
		btn_read_previous.setOnClickListener(this);
		btn_read_check.setOnClickListener(this);

		Bundle bundle = getArguments();
		fromActivity = bundle.getString(Constants.READ_FROM);
		if (null != fromActivity
				&& (Constants.READ_FROM_VALUE.equals(fromActivity) || Constants.READ_FROM_VALUE3.equals(fromActivity))) {
			ll_read_switch_quesition.setVisibility(View.INVISIBLE);
		} else {
			btn_read_check.setVisibility(View.INVISIBLE);
		}

		if (null != fromActivity && Constants.READ_FROM_VALUE1.equals(fromActivity)) {
			downLoadListenTask = new DownLoadListenTask(mContext);
			audioFileDB = new AudioFileDB(mContext);
			mMediaPlayer = new MediaPlayer();
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

			layout_audio_play.setVisibility(View.VISIBLE);
			android.widget.RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) fl_read_btn
					.getLayoutParams();
			layoutParams.setMargins(0, 0, 0, 0);
			fl_read_btn.setLayoutParams(layoutParams);

			iv_listen_play.setOnClickListener(this);
			iv_listen_download.setOnClickListener(this);
		}

		mStartTime = bundle.getString(Constants.READ_START_TIME);
		data = (ArrayList<GroupInfo>) bundle.getSerializable(Constants.READ_SETDATA_PRACTICE);
		switchQuestion(mCurrentGroupId);

		return mView;

	}

	private void toggleButtonStatus(int position) {
		if (position > 0) {
			btn_read_previous.setEnabled(true);
			btn_read_previous.setTextColor(mContext.getResources().getColor(R.color.main_theme_color));
		} else {
			btn_read_previous.setVisibility(View.GONE);
			btn_read_previous.setEnabled(false);
			btn_read_previous.setTextColor(mContext.getResources().getColor(R.color.read_gray_899D9D9D));
		}

		if (position == data.size() - 1) {
			btn_read_next.setText(mContext.getResources().getString(R.string.read_click_submit));
		}
		btn_read_next.setEnabled(false);
		btn_read_next.setTextColor(mContext.getResources().getColor(R.color.read_gray_899D9D9D));
	}

	private void initMediaPlayer() {
		if (null != mMediaPlayer) {
			mMediaPlayer.reset();
			try {
				AudioFile audioinfo = audioFileDB.query(mCurrentGroupInfo.g_id);
				if (TextUtils.isEmpty(audioinfo.audiofile)
						|| !StringUtil.queryFileName(mCurrentGroupInfo.audio).equals(
								StringUtil.queryFileName(audioinfo.audiofile))) {
					mMediaPlayer.setDataSource(mCurrentGroupInfo.audio);
				} else {
					iv_listen_download.setImageResource(R.drawable.download_complete_icon);
					isDownLoad = true;
					mMediaPlayer.setDataSource(audioinfo.audiofile);
				}
				mMediaPlayer.prepareAsync();
				setMediaPlayerListener();
			} catch (Exception e) {
				e.printStackTrace();
				initMediaPlayer();
			}
		}
	}

	/**
	 * 每组题 --切换
	 * 
	 * @param position
	 */
	private void switchQuestion(final int position) {

		mAnswerView.clear();
		mCurrentGroupId = position;
		toggleButtonStatus(position);
		if (data.size() > 0 && mCurrentGroupId < data.size()) {
			mAnswerlist.clear();
			mPointImageView.clear();
			mQuestionView.clear();
			mRightAnswer.clear();
			mMyAnswer.clear();
			ll_read_click_question_point.removeAllViews();
			ll_read_exercises_question.removeAllViews();

			mCurrentGroupInfo = data.get(position);

			initMediaPlayer();

			SubmitGroupInfo submitGroupInfo = ((ReadAllPracticeActivity) mContext).mSubmitReadAnswer.get(Integer
					.valueOf(mCurrentGroupInfo.g_id));

			if (null != submitGroupInfo) {
				submitQuestionInfos = submitGroupInfo.questions;
			}

			mTotalQuestion = mCurrentGroupInfo.questions_list.size();

			tv_fill_smalltitle.setText(String.format(getResources().getString(R.string.read_task_name),
					mCurrentGroupInfo.book_name, mCurrentGroupInfo.task) + " " + mCurrentGroupInfo.group_name);
			tv_read_exercises_title.setText(String.format(mContext.getResources().getString(R.string.read_task_name),
					mCurrentGroupInfo.book_name, mCurrentGroupInfo.task));
			tv_read_exercises_title_detail.setText(mCurrentGroupInfo.group_name);
			tv_read_exercises_content.setText(mCurrentGroupInfo.content);

			iv_read_exercises_pictrue.setOnClickListener(this);
			iv_read_exercises_pictrue2.setOnClickListener(this);
			if (!TextUtils.isEmpty(mCurrentGroupInfo.img_1)) {
				ImageLoader.getInstance().displayImage(mCurrentGroupInfo.img_1, iv_read_exercises_pictrue, options);
			} else {
				ll_read_exercises_pictrue.setVisibility(View.GONE);
			}

			if (!TextUtils.isEmpty(mCurrentGroupInfo.img_2)) {
				ImageLoader.getInstance().displayImage(mCurrentGroupInfo.img_2, iv_read_exercises_pictrue2, options);
			} else {
				ll_read_exercises_pictrue2.setVisibility(View.GONE);
			}

			StringBuilder stringBuilder = new StringBuilder();
			List<Integer> questionId_list = new ArrayList<Integer>();

			StringBuilder sentence_completion_no = new StringBuilder(); // 完成句子题题号

			for (int i = 0; i < mCurrentGroupInfo.questions_list.size(); i++) {

				// 初始化切题的指示小点
				ImageView imageView = new ImageView(mContext);
				imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				imageView.setImageResource(R.drawable.question_point_normal);
				imageView.setPadding(0, 0, 0, mContext.getResources().getDimensionPixelSize(R.dimen.read_16dp));
				mPointImageView.add(imageView);
				ll_read_click_question_point.addView(imageView);

				QuestionInfo questionInfo = mCurrentGroupInfo.questions_list.get(i);
				View questionview = null;
				EditText answeret = null;

				mRightAnswer.add(StringUtil.getRightAnswerList(questionInfo.answer)); // 初始化当前题目的正确答案

				if (Constants.ReadClassifyGroupType.TRUE_OR_FALSE.equals(type)) { // 是非题

					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_click_answer_item1, null);
					TextView tv_read_question = (TextView) questionview.findViewById(R.id.tv_read_question);
					tv_read_question.setText(Html.fromHtml(questionInfo.no + ".  " + questionInfo.question));
					RadioGroup rg = (RadioGroup) questionview.findViewById(R.id.rg_read_click_answer);
					RadioButton rb1 = (RadioButton) questionview.findViewById(R.id.rb_read_click_answer_true);
					RadioButton rb2 = (RadioButton) questionview.findViewById(R.id.rb_read_click_answer_false);
					RadioButton rb3 = (RadioButton) questionview.findViewById(R.id.rb_read_click_answer_notgiven);
					rblist.add(rb1);
					rblist.add(rb2);
					rblist.add(rb3);
					ArrayList<KeyValuePair<String, Boolean>> list = StringUtil.getAnswers(questionInfo.answer);
					try {
						rb1.setText(list.get(0).first);
						rb2.setText(list.get(1).first);
						rb3.setText(list.get(2).first);
					} catch (Exception e) {
						e.printStackTrace();
					}

					rb1.setOnClickListener(this);
					rb2.setOnClickListener(this);
					rb3.setOnClickListener(this);
					rg.setOnCheckedChangeListener(new OnRadioGroupCheckedListener(Integer
							.valueOf(questionInfo.question_id)));

					ll_read_exercises_question.addView(questionview);

					// 上一组 下一组切换时 恢复做过的答案
					if (null != submitQuestionInfos) {
						for (int m = 0; m < submitQuestionInfos.size(); m++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
							if (questionInfo.question_id.equals(submitQuestionInfo.question_id)) {
								for (int k = 0; k < list.size(); k++) {
									if (submitQuestionInfo.answer.equals(list.get(k).first)) {
										switch (k) {
										case 0:
											rb1.performClick();
											break;
										case 1:
											rb2.performClick();
											break;
										case 2:
											rb3.performClick();
											break;
										}
									}
								}
								break;
							}
						}
					}

				} else if (Constants.ReadClassifyGroupType.SINGLE_CHOICE.equals(type)
						|| Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)
						|| Constants.ReadClassifyGroupType.CHOICE_PICTURE.equals(type)) { // 单选题|多选题|带图选择题
					((ReadAllPracticeActivity) mContext)
							.registerOnTouchEventGestureListener(mOnTouchEventGestureListener); // 注册切题时的手势监听
					initViewForChoice(questionInfo);

					mCurrentQuestion = switchChooiseQuestion(0); // 初始化为第一题展示

				}
				if (Constants.ReadClassifyGroupType.SHORT_ANSWER.equals(type)) {// 简答题
					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_fill_answer_item2, null);
					TextView question = (TextView) questionview.findViewById(R.id.tv_read_question);
					answeret = (EditText) questionview.findViewById(R.id.et_read_answer_content);
					answeret.setOnFocusChangeListener(new EditOnFocusChangeListener());
					answeret.addTextChangedListener(new EditTextWatcher(Integer.valueOf(questionInfo.question_id)));
					question.setText(Html.fromHtml(questionInfo.no + ".  "
							+ questionInfo.question.replace(Constants.READ_EDIT_LINE, "")));

					ll_read_exercises_question.addView(questionview);

					// 上一组 下一组切换时 恢复做过的答案
					if (null != submitQuestionInfos) {
						for (int m = 0; m < submitQuestionInfos.size(); m++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
							if (questionInfo.question_id.equals(submitQuestionInfo.question_id)) {
								answeret.requestFocus();
								answeret.setText(submitQuestionInfo.answer);
								answeret.clearFocus();

								ll_read_exercises_question.requestFocus();
								break;
							}
						}
					}
				} else if (Constants.ReadClassifyGroupType.SENTENCE_COMPLETION.equals(type)
						|| Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(type)
						|| Constants.ReadClassifyGroupType.NO_TAB_CHART_COMPLETION.equals(type)) { // 完成句子题|带选项的完成句子题|不带选项卡图表题
					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_fill_answer_item3, null);
					questionId_list.add(Integer.valueOf(questionInfo.question_id));
					if (questionInfo.question.contains(Constants.READ_EDIT_MERGE)) {
						stringBuilder.append(questionInfo.question.replace(Constants.READ_EDIT_MERGE, " "));
						if (TextUtils.isEmpty(sentence_completion_no.toString())) {
							sentence_completion_no.append(questionInfo.no + "-");
						}
					} else {
						stringBuilder.append(questionInfo.question);
						if (questionInfo.no.equals(sentence_completion_no.toString().replace("-", ""))) {
							sentence_completion_no.delete(0, sentence_completion_no.length());
							sentence_completion_no.append(questionInfo.no);
						} else {
							sentence_completion_no.append(questionInfo.no);
						}
						initFlowLayout((FlowLayout) questionview.findViewById(R.id.view_wordwrap_content),
								sentence_completion_no.toString() + ".  " + stringBuilder, questionId_list);
						stringBuilder.delete(0, stringBuilder.length());
						questionId_list.clear();
						sentence_completion_no.delete(0, sentence_completion_no.length());

						ll_read_exercises_question.addView(questionview);
					}

				} else if (Constants.ReadClassifyGroupType.SUMMARY.equals(type)
						|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)) {// 摘要题|带选项摘要题
					stringBuilder.append(questionInfo.question.replace(Constants.READ_EDIT_MERGE, ""));
					questionId_list.add(Integer.valueOf(questionInfo.question_id));
					if (i == mCurrentGroupInfo.questions_list.size() - 1) {
						questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_fill_answer_item3,
								null);
						initFlowLayout((FlowLayout) questionview.findViewById(R.id.view_wordwrap_content),
								stringBuilder.toString(), questionId_list);

						ll_read_exercises_question.addView(questionview);
					}
				} else if (Constants.ReadClassifyGroupType.CHART_COMPLETION.equals(type)) {// 图表题(表格)
					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_fill_answer_item1, null);
					answeret = (EditText) questionview.findViewById(R.id.et_read_answer_content);
					answeret.setOnFocusChangeListener(new EditOnFocusChangeListener());
					answeret.addTextChangedListener(new EditTextWatcher(Integer.valueOf(questionInfo.question_id)));
					TextView tv_read_answer_id = (TextView) questionview.findViewById(R.id.tv_read_answer_id);
					if (TextUtils.isEmpty(stringBuilder.toString())) {
						stringBuilder.append(questionInfo.no);
						tv_read_answer_id.setText(questionInfo.no + ".  ");
					} else if (!stringBuilder.toString().equals(questionInfo.no)) {
						stringBuilder.delete(0, stringBuilder.length());
						stringBuilder.append(questionInfo.no);
						tv_read_answer_id.setText(questionInfo.no + ".  ");
					}

					ll_read_exercises_question.addView(questionview);
					// 上一组 下一组切换时 恢复做过的答案
					if (null != submitQuestionInfos) {
						for (int m = 0; m < submitQuestionInfos.size(); m++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
							if (questionInfo.question_id.equals(submitQuestionInfo.question_id)) {
								answeret.requestFocus();
								answeret.setText(submitQuestionInfo.answer);
								answeret.clearFocus();
								ll_read_exercises_question.requestFocus();
								break;
							}
						}
					}
				}
				if (Constants.ReadClassifyGroupType.TAB_CHART_COMPLETION.equals(type)) {// 带选项卡图表题
					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_tab_answer_item1, null);
					TextView tv_read_answer_content = (TextView) questionview.findViewById(R.id.tv_read_answer_content);
					tv_read_answer_content.setOnClickListener(new OnAnswerClickListener(questionInfo));
					TextView tv_read_answer_id = (TextView) questionview.findViewById(R.id.tv_read_answer_id);

					if (TextUtils.isEmpty(stringBuilder.toString())) {
						stringBuilder.append(questionInfo.no);
						tv_read_answer_id.setText(questionInfo.no + ".  ");
					} else if (!stringBuilder.toString().equals(questionInfo.no)) {
						stringBuilder.delete(0, stringBuilder.length());
						stringBuilder.append(questionInfo.no);
						tv_read_answer_id.setText(questionInfo.no + ".  ");
					}

					ll_read_exercises_question.addView(questionview);
					// 上一组 下一组切换时 恢复做过的答案
					if (null != submitQuestionInfos) {
						for (int m = 0; m < submitQuestionInfos.size(); m++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
							if (questionInfo.question_id.equals(submitQuestionInfo.question_id)) {
								tv_read_answer_content.performClick();
								for (int q = 0; q < items.size(); q++) {
									if (items.get(q).first.equals(submitQuestionInfo.answer)) {
										listView.performItemClick(listView.getChildAt(q), q, q);
										break;
									}
								}
								break;
							}
						}
					}
				} else if (Constants.ReadClassifyGroupType.MATCHING.equals(type)
						|| Constants.ReadClassifyGroupType.LIST_OF_HEADINGS.equals(type)) {// 配对题|标题对应题
					questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_tab_answer_item2, null);
					TextView tv_read_answer_content = (TextView) questionview.findViewById(R.id.tv_read_answer_content);
					tv_read_answer_content.setOnClickListener(new OnAnswerClickListener(questionInfo));
					TextView quesitiontv = (TextView) questionview.findViewById(R.id.tv_read_question);
					quesitiontv.setText(Html.fromHtml(questionInfo.no + ".  " + questionInfo.question));

					ll_read_exercises_question.addView(questionview);
					// 上一组 下一组切换时 恢复做过的答案
					if (null != submitQuestionInfos) {
						for (int m = 0; m < submitQuestionInfos.size(); m++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
							if (questionInfo.question_id.equals(submitQuestionInfo.question_id)) {
								tv_read_answer_content.performClick();
								for (int q = 0; q < items.size(); q++) {
									if (items.get(q).first.equals(submitQuestionInfo.answer)) {
										listView.performItemClick(listView.getChildAt(q), q, q);
										break;
									}
								}
								break;
							}
						}
					}
				}

			}
			scroll_fill_layout.requestFocus();
			scroll_fill_layout.scrollTo(0, 0);
			tv_fill_smalltitle.setVisibility(View.GONE);

		}
	}

	/**
	 * 
	 * 带选项题型点击事件监听（不包括流式布局）
	 *
	 */
	private class OnAnswerClickListener implements OnClickListener {

		private QuestionInfo questionInfo;

		public OnAnswerClickListener(QuestionInfo questionInfo) {
			this.questionInfo = questionInfo;
		}

		@Override
		public void onClick(View v) {
			final TextView content = (TextView) v;
			items = StringUtil.getAnswers(questionInfo.answer);
			KeyValuePair<AlertDialog, ListView> keyValuePair = AppUtil.showSingleListDialog(getActivity(), items,
					new OnItemClickListener() {

						@SuppressLint("NewApi")
						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							String str = items.get(position).first;
							content.setText(str);
							ArrayList<String> list = new ArrayList<String>();
							list.add(str);
							mMyAnswer.put(Integer.valueOf(questionInfo.question_id), list);

							if (!mAnswerlist.contains(Integer.valueOf(questionInfo.question_id))) {
								mAnswerlist.add(Integer.valueOf(questionInfo.question_id));
							}

							if (null != content.getText() || content.getText().toString().length() > 0) {
								content.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, null, null);
							} else {
								content.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.tab_icon, 0, 0, 0);
							}
							alertDialog.cancel();

							switchCheckBtnState();
						}
					});

			alertDialog = keyValuePair.first;
			listView = keyValuePair.second;
		}
	}

	private int addview_i = 0;

	/**
	 * 初始化 流式布局界面---如摘要题、完成句子题
	 * 
	 * @param view_wordwrap_content
	 * @param quesition
	 * @param question_id
	 */
	private void initFlowLayout(FlowLayout view_wordwrap_content, String quesition, List<Integer> question_id) {
		MarginLayoutParams layoutParams = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,
				MarginLayoutParams.WRAP_CONTENT);
		layoutParams.setMargins(0, DensityUtil.dip2px(mContext, 3), DensityUtil.dip2px(mContext, 3),
				DensityUtil.dip2px(mContext, 3));

		String regEx = "[.|!|?]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(quesition);
		String[] strss = p.split(quesition);
		if (strss.length > 0) {
			int count = 0;
			while (count < strss.length) {
				if (m.find()) {
					strss[count] += m.group();
				}
				count++;
			}
		}
		int i = 0;
		for (String strsss : strss) {
			String[] str1s = strsss.split(" ");

			for (String str : str1s) {
				if (str.contains(Constants.READ_EDIT_LINE)) {

					final EditText edittext = (EditText) LayoutInflater.from(getActivity()).inflate(
							R.layout.wordwrap_edit, null);
					edittext.setLayoutParams(layoutParams);
					if (Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(type)
							|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)) {
						edittext.setInputType(InputType.TYPE_NULL);
						edittext.setSingleLine(false);
						edittext.setOnTouchListener(new OnAnswerTouchListener(mCurrentGroupInfo.questions_list
								.get(addview_i)));
						Drawable drawble = getResources().getDrawable(R.drawable.tab_icon);
						drawble.setBounds(0, 0, drawble.getIntrinsicWidth(), drawble.getIntrinsicHeight());
						edittext.setCompoundDrawables(drawble, null, null, null);
					} else {
						edittext.setOnFocusChangeListener(new OnWrapEditFocusChangeListener());
						edittext.addTextChangedListener(new EditTextWatcher(question_id.get(i)));
					}
					edittext.setTextSize(16);
					edittext.setPadding(DensityUtil.dip2px(mContext, 5), 0, DensityUtil.dip2px(mContext, 5), 0);
					edittext.setTag(strsss);
					edittext.setCursorVisible(true);
					edittext.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
						@Override
						public void onGlobalLayout() {
							int heightDiff = edittext.getRootView().getHeight() - edittext.getHeight();
							if (heightDiff > 100) { // 如果高度差超过100像素，就很有可能是有软键盘...

							} else {

							}
						}
					});

					if (null != submitQuestionInfos) { // 恢复选择的答案

						for (int j = 0; j < submitQuestionInfos.size(); j++) {
							SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(j);
							if (question_id.get(i).equals(Integer.valueOf(submitQuestionInfo.question_id))) {
								edittext.requestFocus();
								if (Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(type)
										|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)) {
									edittext.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),
											SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, edittext.getLeft() + 5,
											edittext.getTop() + 5, 0));
									for (int q = 0; q < items.size(); q++) {
										if (items.get(q).first.equals(submitQuestionInfo.answer)) {
											listView.performItemClick(listView.getChildAt(q), q, q);
											break;
										}
									}
								} else {
									edittext.setText(submitQuestionInfo.answer);
								}
							}
						}
					}

					edittext.setGravity(Gravity.START);
					edittext.clearFocus();
					view_wordwrap_content.addView(edittext);
					addview_i++;
					i++;

				} else {
					TextView textview = new TextView(getActivity());
					textview.setLayoutParams(layoutParams);
					textview.setTextSize(16);
					textview.setText(Html.fromHtml(str));
					textview.setTextColor(Color.BLACK);
					view_wordwrap_content.addView(textview);
				}
			}
		}

	}

	private class OnWrapEditFocusChangeListener implements OnFocusChangeListener {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			EditText edittext = (EditText) v;
			if (hasFocus) {
				edittext.setCompoundDrawables(null, null, null, null);
				InputMethodManager inputManager = (InputMethodManager) edittext.getContext().getSystemService(
						Context.INPUT_METHOD_SERVICE);
				inputManager.showSoftInput(edittext, 0);
			} else {
				if (edittext.getText().toString().length() == 0) {
					Drawable drawble = getResources().getDrawable(R.drawable.practice_pen);
					drawble.setBounds(0, 0, drawble.getIntrinsicWidth(), drawble.getIntrinsicHeight());
					edittext.setCompoundDrawables(drawble, null, null, null);
				}
			}

		}

	}

	private class OnAnswerTouchListener implements OnTouchListener {

		private QuestionInfo questionInfo;
		private boolean isMove;
		private float x;
		private float y;

		public OnAnswerTouchListener(QuestionInfo questionInfo) {
			this.questionInfo = questionInfo;
		}

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				x = event.getX();
				y = event.getY();
				break;
			case MotionEvent.ACTION_MOVE:
				if (x != event.getX() && y != event.getY()) {
					isMove = true;
				} else {
					isMove = false;
				}
				break;
			case MotionEvent.ACTION_UP:
				if (!isMove) {
					isMove = false;
					final EditText content = (EditText) v;
					items = StringUtil.getAnswers(questionInfo.answer);
					KeyValuePair<AlertDialog, ListView> keyValuePair = AppUtil.showSingleListDialog(mContext, items,
							new OnItemClickListener() {

								@Override
								public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
									String str = items.get(position).first;
									if (Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)
											|| Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(type)) {
										content.setText(StringUtil.deleteNo(str));
									} else {
										content.setText(str);
									}
									content.setSelection(content.getText().length());

									ArrayList<String> list = new ArrayList<String>();
									list.add(str);
									mMyAnswer.put(Integer.valueOf(questionInfo.question_id), list);

									if (!mAnswerlist.contains(Integer.valueOf(questionInfo.question_id))) {
										mAnswerlist.add(Integer.valueOf(questionInfo.question_id));
									}

									if (content.getText().toString().length() == 0) {
										Drawable drawble = getResources().getDrawable(R.drawable.tab_icon);
										drawble.setBounds(0, 0, drawble.getIntrinsicWidth(),
												drawble.getIntrinsicHeight());
										content.setCompoundDrawables(drawble, null, null, null);
									} else {
										content.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0);
									}

									alertDialog.cancel();

									switchCheckBtnState();
								}
							});

					alertDialog = keyValuePair.first;
					listView = keyValuePair.second;
				}
				break;
			default:
				isMove = false;
				break;

			}

			return false;
		}

	}

	/**
	 * 
	 * EditText文本监听器
	 */
	private class EditTextWatcher implements TextWatcher {
		private Integer question_id;
		private boolean isFirst;

		public EditTextWatcher(Integer question_id) {
			this.question_id = question_id;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			if (null == s || s.toString().length() == 0) {
				isFirst = true;
			} else {
				isFirst = false;
			}
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (null == s || s.toString().length() == 0) {
				if (mAnswerCount > 0) {
					mAnswerCount--;
					mAnswerlist.remove(mAnswerCount);
				}
			} else {
				if (start == 0 && isFirst && mAnswerCount < mTotalQuestion) {
					mAnswerlist.add(mAnswerCount++);
				}
			}

			switchCheckBtnState();
		}

		@Override
		public void afterTextChanged(Editable s) {
			ArrayList<String> list = new ArrayList<String>();
			list.add(s.toString());

			mMyAnswer.put(question_id, list);

		}
	}

	/**
	 * EditText焦点变化监听器
	 * 
	 *
	 */
	private class EditOnFocusChangeListener implements OnFocusChangeListener {

		@SuppressLint("NewApi")
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			EditText editText = (EditText) v;

			if (hasFocus) {
				editText.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0);
			} else {
				if (null == editText.getText() || editText.getText().toString().length() == 0) {
					editText.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.practice_pen, 0, 0, 0);
				}
			}

		}
	}

	/**
	 * 听力模考-播放器设置监听
	 */
	private void setMediaPlayerListener() {
		mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mp) {
				// if (mProgressDialog != null && mProgressDialog.isShowing()) {
				// mProgressDialog.cancel();
				// }
				int max = mMediaPlayer.getDuration();
				seekbar_self.setMax(max);
			}
		});

		mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				releaseTimer();
				iv_listen_play.setImageResource(R.drawable.play_icon);
				// setPlayButtonImage(false);
			}
		});
		mMediaPlayer.setOnInfoListener(new OnInfoListener() {

			@Override
			public boolean onInfo(MediaPlayer mp, int what, int extra) {
				switch (what) {
				case MediaPlayer.MEDIA_INFO_BUFFERING_END:
					int duration = mMediaPlayer.getDuration();
					if (duration > 0) {
						seekbar_self.setMax(duration);
					}
					break;
				}
				return false;
			}
		});
		mMediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

			@Override
			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				// seekbar_self.setSecondaryProgress(percent);
			}
		});

		seekbar_self.setOnSeekBarChangeListener(new SeekBarChangeEvent());

	}

	/**
	 * RadioGroup监听器
	 *
	 */
	private class OnRadioGroupCheckedListener implements android.widget.RadioGroup.OnCheckedChangeListener {

		private Integer quesition_id;

		public OnRadioGroupCheckedListener(Integer quesition_id) {
			this.quesition_id = quesition_id;
		}

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			int radioButtonId = group.getCheckedRadioButtonId();
			// 根据ID获取RadioButton的实例
			RadioButton rb = (RadioButton) mView.findViewById(radioButtonId);

			mMyCurrentAnswer = new ArrayList<String>();
			// 更新文本内容，以符合选中项
			mMyCurrentAnswer.add(rb.getText().toString());
			mMyAnswer.put(quesition_id, mMyCurrentAnswer);
			mAnswerlist.clear();
			for (int i = 0; i < mMyAnswer.size(); i++) {
				mAnswerlist.add(i);

				switchCheckBtnState();
			}
		}

	}

	/**
	 * 选择题 -切换
	 * 
	 * @param number
	 * @return
	 */
	private int switchChooiseQuestion(int number) {

		mMyCurrentAnswer = new ArrayList<String>();
		mAnswerCount = 0;

		if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)) {
			mTotalAnswer = JSONArray.parseArray(mCurrentGroupInfo.questions_list.get(number).answer).size();
		}

		if (number == mTotalQuestion - 1) {
			if (null != fromActivity
					&& (Constants.READ_FROM_VALUE.equals(fromActivity) || Constants.READ_FROM_VALUE3
							.equals(fromActivity))) {
				btn_read_check.setVisibility(View.VISIBLE);
			} else {
				ll_read_switch_quesition.setVisibility(View.VISIBLE);
			}
		} else {
			ll_read_switch_quesition.setVisibility(View.GONE);
			btn_read_check.setVisibility(View.GONE);
		}

		ll_read_exercises_question.removeAllViews();
		ll_read_exercises_question.addView(mQuestionView.get(number));

		if (mPointImageView.size() > 1) {
			ll_read_click_question_point.setVisibility(View.VISIBLE);

			for (int i = 0; i < mPointImageView.size(); i++) {
				if (i == number) {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_checked);
				} else {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_normal);
				}
			}
		}

		/**
		 * 重置上一次选择的答案
		 */
		ArrayList<CheckBox> checkBox = checkBoxs
				.get(Integer.valueOf(mCurrentGroupInfo.questions_list.get(number).question_id));
		for (int k = 0; k < checkBox.size(); k++) {
			checkBox.get(k).performClick(); // 模拟点击事件
		}
		RadioButton rButton = radioButton
				.get(Integer.valueOf(mCurrentGroupInfo.questions_list.get(number).question_id));
		if (null != rButton) {
			rButton.performClick();
		}

		return number;
	}

	/**
	 * 查看答案解析 - 切换
	 * 
	 * @param number
	 * @return
	 */
	private int switchLookAnswer(int number) {

		if (number == mTotalQuestion - 1) {
			btn_read_check.setVisibility(View.VISIBLE);
		} else {
			btn_read_check.setVisibility(View.GONE);
		}

		ll_read_exercises_question.removeAllViews();
		ll_read_exercises_question.addView(mAnswerView.get(number));

		if (mPointImageView.size() > 1) {
			ll_read_click_question_point.setVisibility(View.VISIBLE);
			for (int i = 0; i < mPointImageView.size(); i++) {
				if (i == number) {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_checked);
				} else {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_normal);
				}
			}
		}

		return number;
	}

	/**
	 * 选择题 --初始化界面
	 * 
	 * @param quesition
	 */
	private void initViewForChoice(QuestionInfo quesition) {
		ArrayList<CheckBox> checkBoxlist = new ArrayList<CheckBox>();
		RadioButton rButton = null;

		View questionview = LayoutInflater.from(mContext).inflate(R.layout.layout_read_click_answer_item2, null);

		TextView qusitiontv = (TextView) questionview.findViewById(R.id.tv_read_question);
		qusitiontv.setText(Html.fromHtml(quesition.no + ".  " + quesition.question));
		LinearLayout ll_read_exercises_answer = (LinearLayout) questionview.findViewById(R.id.ll_read_exercises_answer);
		RadioGroup rg_read_click_answer = (RadioGroup) questionview.findViewById(R.id.rg_read_click_answer);

		JSONArray array = JSONArray.parseArray(quesition.answer);
		String recoverAnswer = "";
		if (null != submitQuestionInfos) { // 上一组 下一组切换时 恢复做过的答案
			for (int m = 0; m < submitQuestionInfos.size(); m++) {
				SubmitQuestionInfo submitQuestionInfo = submitQuestionInfos.get(m);
				if (quesition.question_id.equals(submitQuestionInfo.question_id)) {
					recoverAnswer = submitQuestionInfo.answer;
					break;
				}
			}
		}

		for (int i = 0; i < array.size(); i++) {
			AnswerInfo answerInfo = array.getObject(i, AnswerInfo.class);

			if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)) {

				CheckBox answerview = (CheckBox) LayoutInflater.from(mContext).inflate(
						R.layout.layout_read_click_answer_checkbox, null);
				answerview.setText(answerInfo.text);
				answerview.setOnCheckedChangeListener(new CheckBoxOnCheckedChangeListener(Integer
						.valueOf(quesition.question_id)));

				if (!TextUtils.isEmpty(recoverAnswer)) {
					List<String> answerlist = StringUtil.getAnswerList(recoverAnswer);
					for (int k = 0; k < answerlist.size(); k++) {
						if (answerlist.get(k).equals(answerInfo.text)) {
							checkBoxlist.add(answerview);
							break;
						}
					}
				}

				rg_read_click_answer.setVisibility(View.GONE);
				ll_read_exercises_answer.addView(answerview);
			} else if (Constants.ReadClassifyGroupType.SINGLE_CHOICE.equals(type)
					|| Constants.ReadClassifyGroupType.CHOICE_PICTURE.equals(type)) {
				RadioButton answerview = (RadioButton) LayoutInflater.from(mContext).inflate(
						R.layout.layout_read_click_answer_radiobtn, null);
				rg_read_click_answer.addView(answerview, new LayoutParams(LayoutParams.MATCH_PARENT,
						LayoutParams.WRAP_CONTENT));
				answerview.setText(answerInfo.text);
				rg_read_click_answer.setOnCheckedChangeListener(new OnRadioGroupCheckedListener(Integer
						.valueOf(quesition.question_id)));

				if (!TextUtils.isEmpty(recoverAnswer)) {
					if (recoverAnswer.equals(answerInfo.text)) {
						rButton = answerview;
					}
				}
			}
		}

		mQuestionView.add(questionview);
		checkBoxs.put(Integer.valueOf(quesition.question_id), checkBoxlist);
		radioButton.put(Integer.valueOf(quesition.question_id), rButton);

	}

	/**
	 * CheckBox状态改变监听器
	 *
	 */
	private class CheckBoxOnCheckedChangeListener implements OnCheckedChangeListener {

		private Integer quesition_id;

		public CheckBoxOnCheckedChangeListener(Integer quesition_id) {
			this.quesition_id = quesition_id;

		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if (isChecked) {
				if (mAnswerCount < mTotalAnswer) {
					mAnswerCount++;
					mMyCurrentAnswer.add(buttonView.getText().toString());
				}
			} else {
				if (mAnswerCount > 0) {
					mAnswerCount--;
					mMyCurrentAnswer.remove(buttonView.getText().toString());
				}
			}

			if (mAnswerCount > 0) {
				if (!mAnswerlist.contains(quesition_id)) {
					mAnswerlist.add(quesition_id);
				}
			} else {
				mAnswerlist.remove(quesition_id);
			}

			mMyAnswer.put(Integer.valueOf(quesition_id), mMyCurrentAnswer);

			switchCheckBtnState();
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.iv_read_exercises_pictrue:
			Intent intent = new Intent(mContext, PhotoViewActivity.class);
			intent.putExtra(Constants.READ_IMG_URL, mCurrentGroupInfo.img_1);
			startActivity(intent);
			break;

		case R.id.iv_read_exercises_pictrue2:
			Intent intent2 = new Intent(mContext, PhotoViewActivity.class);
			intent2.putExtra(Constants.READ_IMG_URL, mCurrentGroupInfo.img_2);
			startActivity(intent2);
			break;

		case R.id.rb_read_click_answer_false:

		case R.id.rb_read_click_answer_notgiven:

		case R.id.rb_read_click_answer_true:
			for (int i = 0; i < rblist.size(); i++) {
				RadioButton rb = rblist.get(i);
				if (rb.isChecked()) {
					rb.setTextColor(mContext.getResources().getColor(R.color.white));
				} else {
					rb.setTextColor(mContext.getResources().getColor(R.color.gray));
				}
			}

			switchCheckBtnState();

			break;

		case R.id.btn_read_previous: // 上一组
			saveAnswer();
			listener.changeFragment(mCurrentGroupId - 1);
			break;

		case R.id.btn_read_next: // 下一组
			saveAnswer();
			listener.changeFragment(mCurrentGroupId + 1);
			break;
		case R.id.btn_read_check:// 继续答题|检查答案
			Button btn = (Button) v;

			scroll_fill_layout.scrollTo(0, 0);
			tv_fill_smalltitle.setVisibility(View.GONE);

			if (mContext.getResources().getString(R.string.read_continue_answer).equals(btn.getText().toString())) {
				if (data.size() > mCurrentGroupId + 1) {
					((ReadAllPracticeActivity) mContext)
							.unregisterOnTouchEventGestureListener(mOnTouchEventGestureListener);
					mIsLookAnswer = false;
					ll_read_click_question_point.setVisibility(View.INVISIBLE);
					// tv_read_exercises_title.setVisibility(View.VISIBLE);
					btn_read_check.setText(mContext.getResources().getString(R.string.read_check_answer));
					btn_read_check.setEnabled(false);
					btn_read_check.setTextColor(mContext.getResources().getColor(R.color.read_gray_899D9D9D));
				}
				listener.changeFragment(mCurrentGroupId + 1);
			} else if (mContext.getResources().getString(R.string.read_check_answer).equals(btn.getText().toString())) {
				if (fromActivity.equals(Constants.READ_FROM_VALUE)) {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "readPractice_checkAnswer");
				} else {
					// 友盟统计
					MobclickAgent.onEvent(mContext, "ErrorPractice_checkAnswer");
				}
				InputMethodManager inputManager = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
				((ReadAllPracticeActivity) mContext).resetTopTitle(R.string.read_answer_analysis_title);
				addAnswerAnalysisView();
				ll_read_exercises_question.removeAllViews();
				// tv_read_exercises_title.setVisibility(View.GONE);
				btn_read_check.setText(mContext.getResources().getString(R.string.read_continue_answer));
				if (Constants.ReadClassifyGroupType.SUMMARY.equals(type)
						|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)) {
					for (int i = 0; i < mAnswerView.size(); i++) {
						ll_read_exercises_question.addView(mAnswerView.get(i));
					}
				} else {
					((ReadAllPracticeActivity) mContext)
							.registerOnTouchEventGestureListener(mOnTouchEventGestureListener);
					mIsLookAnswer = true;
					mCurrentQuestion = switchLookAnswer(0);
				}
			}

			break;
		case R.id.iv_listen_play:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "listenContent_startPlay");

			if (NetworkUtil.isNetworkAvailable(mContext) || isDownLoad) {
				switchPlay();
			} else {
				AppUtil.showToast(mContext, R.string.no_network);
			}
			break;
		case R.id.iv_listen_download:
			// 友盟统计
			MobclickAgent.onEvent(mContext, "listenContent_downloadClick");

			if (!isDownLoad) {
				isDownLoad = true;
				downloadFile();
			}
			break;
		default:
			break;
		}

	}

	private void switchPlay() {
		if (mMediaPlayer.isPlaying()) {
			mToPlay = false;
			mMediaPlayer.pause();
			releaseTimer();
			iv_listen_play.setImageResource(R.drawable.play_icon);
		} else {
			mMediaPlayer.start();
			startTimer();
			mToPlay = true;
			iv_listen_play.setImageResource(R.drawable.pause_icon);
		}
	}

	private void downloadFile() {
		// 判断是否有外部存储卡
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {
			AppUtil.showToast(mContext, "外部存储不可用");
			return;
		}
		File file = new File(SDcardUtil.setDestinationInExternalPublicDir(),
				StringUtil.queryFileName(mCurrentGroupInfo.audio));

		if (file.exists()) {
			file.delete();
		}

		final String mFilePath = file.getAbsolutePath();
		if (NetworkUtil.isNetworkAvailable(mContext)) {
			downLoadListenTask.downloadListen(mCurrentGroupInfo.audio, mFilePath, new RequestCallBack<File>() {

				@Override
				public void onStart() {
					fl_loading.setVisibility(View.VISIBLE);
					iv_listen_download.setVisibility(View.GONE);
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					LogUtils.e(arg0.getMessage() + "-----" + arg1);
					isDownLoad = false;
					AppUtil.showToast(mContext, R.string.listen_download_fail);
					fl_loading.setVisibility(View.GONE);
					iv_listen_download.setVisibility(View.VISIBLE);

				}

				@Override
				public void onSuccess(ResponseInfo<File> arg0) {
					iv_listen_download.setImageResource(R.drawable.download_complete_icon);
					fl_loading.setVisibility(View.GONE);
					iv_listen_download.setVisibility(View.VISIBLE);
					AudioFile audioFile = new AudioFile();
					audioFile.g_id = mCurrentGroupInfo.g_id;
					audioFile.category_id = mCurrentGroupInfo.category_id;
					audioFile.audiofile = mFilePath;
					audioFileDB.replaceInto(audioFile);

				}

			});
		} else {
			AppUtil.showToast(mContext, R.string.no_network);
		}
	}

	/**
	 * 剑雅真题 -保存答案
	 * 
	 */
	private void saveAnswer() {
		SubmitGroupInfo submitGroupInfo = new SubmitGroupInfo();
		ArrayList<SubmitQuestionInfo> submitQuestionInfos = new ArrayList<SubmitQuestionInfo>();
		for (int i = 0; i < mTotalQuestion; i++) {
			SubmitQuestionInfo submitQuestionInfo = new SubmitQuestionInfo();
			List<String> myAnswerlist = mMyAnswer
					.get(Integer.valueOf(mCurrentGroupInfo.questions_list.get(i).question_id));

			if (null != myAnswerlist) {
				submitQuestionInfo.question_id = mCurrentGroupInfo.questions_list.get(i).question_id;
				submitQuestionInfo.answer = StringUtil.getAnswerStr(myAnswerlist);

				submitQuestionInfo.is_right = "true";
				for (int j = 0; j < myAnswerlist.size(); j++) {
					if (!StringUtil.contains(mRightAnswer.get(i), myAnswerlist.get(j))) {
						submitQuestionInfo.is_right = "false";
					}
				}

				if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)
						&& myAnswerlist.size() != mRightAnswer.get(i).size()) {
					submitQuestionInfo.is_right = "false";
				}

				mCurrentGroupInfo.questions_list.get(i).is_right = submitQuestionInfo.is_right;

				submitQuestionInfos.add(submitQuestionInfo);

			}
		}

		submitGroupInfo.g_id = mCurrentGroupInfo.g_id;
		submitGroupInfo.start_time = mStartTime;
		submitGroupInfo.finish_time = String.valueOf(System.currentTimeMillis());
		submitGroupInfo.questions = submitQuestionInfos;
		((ReadAllPracticeActivity) mContext).mSubmitReadAnswer.put(Integer.valueOf(mCurrentGroupInfo.g_id),
				submitGroupInfo);
		((ReadAllPracticeActivity) mContext).mInstantReportGroupInfoList.put(Integer.valueOf(mCurrentGroupInfo.g_id),
				mCurrentGroupInfo);
	}

	private void switchCheckBtnState() {
		if (mAnswerlist.size() == mTotalQuestion) {
			btn_read_next.setEnabled(true);
			btn_read_next.setTextColor(mContext.getResources().getColor(R.color.main_theme_color));
			btn_read_check.setEnabled(true);
			btn_read_check.setTextColor(mContext.getResources().getColor(R.color.main_theme_color));
		} else {
			btn_read_next.setEnabled(false);
			btn_read_next.setTextColor(mContext.getResources().getColor(R.color.read_gray_899D9D9D));
			btn_read_check.setEnabled(false);
			btn_read_check.setTextColor(mContext.getResources().getColor(R.color.read_gray_899D9D9D));
		}
	}

	public void onFragmentBack() {
		((ReadAllPracticeActivity) mContext).unregisterOnTouchEventGestureListener(mOnTouchEventGestureListener);

		if (mMediaPlayer != null) {
			mMediaPlayer.pause();
			mMediaPlayer.stop();
			mMediaPlayer.release();
			mMediaPlayer.setOnPreparedListener(null);
			mMediaPlayer.setOnCompletionListener(null);
			mMediaPlayer.setOnInfoListener(null);
			mMediaPlayer.setOnBufferingUpdateListener(null);
			mMediaPlayer = null;
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("from=" + fromActivity + "||type=" + type);
		MobclickAgent.onResume(mContext);

		myLayoutTop = ll_read_top.getBottom();// 获取searchLayout的顶部位置
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("from=" + fromActivity + "||type=" + type);
		MobclickAgent.onPause(mContext);
	}

	@Override
	public void onScroll(int scrollY) {
		myLayoutTop = ll_read_top.getBottom();// 获取searchLayout的顶部位置
		if (scrollY >= myLayoutTop) {
			tv_fill_smalltitle.setVisibility(View.VISIBLE);
		} else {
			tv_fill_smalltitle.setVisibility(View.GONE);
		}
	}

	/**
	 * 添加答案解析view集合
	 */
	private void addAnswerAnalysisView() {

		SubmitGroupInfo submitGroupInfo = new SubmitGroupInfo();
		ArrayList<SubmitQuestionInfo> submitQuestionInfos = new ArrayList<SubmitQuestionInfo>();
		for (int i = 0; i < mTotalQuestion; i++) {
			SubmitQuestionInfo submitQuestionInfo = new SubmitQuestionInfo();
			List<String> myAnswerlist = mMyAnswer
					.get(Integer.valueOf(mCurrentGroupInfo.questions_list.get(i).question_id));

			submitQuestionInfo.question_id = mCurrentGroupInfo.questions_list.get(i).question_id;
			submitQuestionInfo.answer = StringUtil.getAnswerStr(myAnswerlist);

			submitQuestionInfo.is_right = "true";
			for (int j = 0; j < myAnswerlist.size(); j++) {
				if (!StringUtil.contains(mRightAnswer.get(i), myAnswerlist.get(j))) {
					submitQuestionInfo.is_right = "false";
				}
			}

			if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)
					&& myAnswerlist.size() != mRightAnswer.get(i).size()) {
				submitQuestionInfo.is_right = "false";
			}

			mCurrentGroupInfo.questions_list.get(i).is_right = submitQuestionInfo.is_right;
			submitQuestionInfos.add(submitQuestionInfo);

			View analysisview = null;

			if (Constants.ReadClassifyGroupType.SUMMARY.equals(type)
					|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)) {
				analysisview = LayoutInflater.from(mContext).inflate(R.layout.layout_summary_answer_anlysis, null);
			} else {
				analysisview = LayoutInflater.from(mContext).inflate(R.layout.layout_answer_analysis, null);
			}

			TextView youranswer = (TextView) analysisview.findViewById(R.id.tv_read_your_answer);
			TextView rightanswer = (TextView) analysisview.findViewById(R.id.tv_read_right_answer);
			TextView answeranalysis = (TextView) analysisview.findViewById(R.id.tv_read_answer_analysis);
			TextView tv_read_question = (TextView) analysisview.findViewById(R.id.tv_read_question);

			TextView analysistv = (TextView) analysisview.findViewById(R.id.tv_read_answer_analysis_title);
			if (!TextUtils.isEmpty(mCurrentGroupInfo.questions_list.get(i).describe)) {
				answeranalysis.setText(mCurrentGroupInfo.questions_list.get(i).describe);
			} else {
				analysistv.setVisibility(View.GONE);
				answeranalysis.setVisibility(View.GONE);
			}

			String questionstr = mCurrentGroupInfo.questions_list.get(i).question;
			questionstr = questionstr.replace(Constants.READ_EDIT_MERGE, " ");
			if (null != tv_read_question) {
				youranswer.setTextColor(getResources().getColor(R.color.ask_right));
				if (Constants.READ_EDIT_LINE.equals(questionstr)) {
					questionstr = "";
				}
				tv_read_question.setText(Html.fromHtml(mCurrentGroupInfo.questions_list.get(i).no
						+ ".  "
						+ questionstr.replace(Constants.READ_EDIT_LINE,
								mContext.getResources().getString(R.string.read_text_under_line))));
				rightanswer.setText(StringUtil.getAnswerStr(mRightAnswer.get(i)));
				if (submitQuestionInfo.is_right.equals("false")) {
					if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(type)) { // 多选题，单独标红
						SpannableStringBuilder builder = new SpannableStringBuilder();

						for (int j = 0; j < myAnswerlist.size(); j++) {
							builder.append(myAnswerlist.get(j) + "\r\n");
							if (!StringUtil.contains(mRightAnswer.get(i), myAnswerlist.get(j))) {
								ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.ask_wrong));
								builder.setSpan(redSpan, builder.length() - (myAnswerlist.get(j).length() + 2),
										builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							}
						}
						youranswer.setText(builder);
					} else {
						youranswer.setTextColor(getResources().getColor(R.color.ask_wrong));
						youranswer.setText(StringUtil.getAnswerStr(myAnswerlist));
					}
				} else {
					youranswer.setText(StringUtil.getAnswerStr(myAnswerlist));
				}
			} else {
				FlowLayout summary_tv_read_question = (FlowLayout) analysisview
						.findViewById(R.id.tv_summary_read_question);
				MarginLayoutParams layoutParams = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,
						MarginLayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, DensityUtil.dip2px(mContext, 3), DensityUtil.dip2px(mContext, 3),
						DensityUtil.dip2px(mContext, 3));
				rightanswer.setText(StringUtil.getAnswerStr(mRightAnswer.get(i)));
				String regEx = "[.|!|?]";
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(questionstr);
				String[] strss = p.split(questionstr);
				if (strss.length > 0) {
					int count = 0;
					while (count < strss.length) {
						if (m.find()) {
							strss[count] += m.group();
						}
						count++;
					}
				}
				for (String strsss : strss) {
					String[] str1s = strsss.split(" ");

					for (String str : str1s) {
						if (str.contains(Constants.READ_EDIT_LINE)) {

							final EditText edittext = (EditText) LayoutInflater.from(getActivity()).inflate(
									R.layout.wordwrap_edit, null);
							edittext.setLayoutParams(layoutParams);
							edittext.setPadding(DensityUtil.dip2px(mContext, 5), 0, DensityUtil.dip2px(mContext, 5), 0);
							edittext.setInputType(InputType.TYPE_NULL);
							edittext.setSingleLine(false);
							edittext.setTextSize(16);
							edittext.setTag(strsss);
							edittext.setTextColor(getResources().getColor(R.color.ask_right));
							if (Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(type)
									|| Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(type)) {
								edittext.setText(StringUtil.deleteNo(StringUtil.getAnswerStr(myAnswerlist)));
							} else {
								edittext.setText(StringUtil.getAnswerStr(myAnswerlist));
							}
							if (submitQuestionInfo.is_right.equals("false")) {
								edittext.setTextColor(getResources().getColor(R.color.ask_wrong));
							}
							edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0);
							summary_tv_read_question.addView(edittext);
							edittext.setGravity(Gravity.CENTER);
						} else {
							TextView textview = new TextView(getActivity());
							textview.setLayoutParams(layoutParams);
							textview.setPadding(0, 0, 0, 0);
							textview.setTextSize(16);
							textview.setText(Html.fromHtml(str));
							textview.setTextColor(Color.BLACK);
							summary_tv_read_question.addView(textview);
						}
					}
				}
			}

			mAnswerView.add(analysisview);
		}

		submitGroupInfo.g_id = mCurrentGroupInfo.g_id;
		submitGroupInfo.start_time = mStartTime;
		submitGroupInfo.finish_time = String.valueOf(System.currentTimeMillis());
		submitGroupInfo.questions = submitQuestionInfos;
		((ReadAllPracticeActivity) mContext).mSubmitReadAnswer.put(Integer.valueOf(mCurrentGroupInfo.g_id),
				submitGroupInfo);

	}

	@Override
	public void isScrollBottom(boolean isBottom) {
		isScrollBottom = isBottom;
	}

	@Override
	public void isScrollTop(boolean isTop) {
		isScrollTop = isTop;
	}

	// 进度改变
	class SeekBarChangeEvent implements OnSeekBarChangeListener {
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

			if (mUserDagDBar) {
				mMediaPlayer.seekTo(progress);
				setProgressText(progress);
			}

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// if (mToPlay) {
			// mMediaPlayer.pause();
			// iv_listen_play.setImageResource(R.drawable.play_icon);
			// releaseTimer();
			// }
			mUserDagDBar = true;
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// if (mToPlay) {
			// mMediaPlayer.start();
			// iv_listen_play.setImageResource(R.drawable.pause_icon);
			// startTimer();
			// }
			mUserDagDBar = false;
		}

	}

	private void releaseTimer() {
		if (null != mTimer) {
			mTimer.cancel();
			mTimer = null;
		}
		if (null != mTimerTask) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	private void startTimer() {
		releaseTimer();

		mTimerTask = new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(0);
			}
		};

		mTimer = new Timer();
		mTimer.schedule(mTimerTask, 0, 1000);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				if (mMediaPlayer != null) {
					int currentDuration = mMediaPlayer.getCurrentPosition();
					int duration = mMediaPlayer.getDuration();
					// 在onPrepare中获得duration可能为0，所以在这再一次设置max
					if (seekbar_self.getMax() == 0 && duration > 0) {
						seekbar_self.setMax(duration);
					}
					seekbar_self.setProgress(currentDuration);
					setProgressText(currentDuration);
				}
			}

		}
	};

	private void setProgressText(int duration) {
		duration = duration / 1000;
		StringBuilder sb = new StringBuilder();
		int m = duration / 60;
		if (m == 0) {
			sb.append("00:");
		} else if (m < 10) {
			sb.append("0").append(m).append(":");
		} else {
			sb.append(m).append(";");
		}
		int s = duration % 60;
		if (s < 10) {
			sb.append("0").append(s);
		} else {
			sb.append(s);
		}
		tv_play_time.setText(sb.toString());
	}

}
